<template>
  <div class="app-container ">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="收费站" prop="deptId" v-if="deptId==101">
        <el-tree-select style="width: 100%;" v-model="queryParams.deptId" :data="deptOptions" :props="{ value: 'id', label: 'label', children: 'children' }"
          value-key="id" placeholder="请选择" check-strictly />
      </el-form-item>
      <el-form-item label="月份" style="width: 308px">
        <el-date-picker v-model="queryParams.month" value-format="YYYY-MM" type="month"></el-date-picker>
      </el-form-item>
      <el-form-item label="值班日期" prop="guardDate">
        <el-date-picker clearable v-model="queryParams.guardDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择值班日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['coordination:guard:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['coordination:guard:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport" v-hasPermi="['coordination:guard:import']">导入</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="guardList" @selection-change="handleSelectionChange" show-overflow-tooltip>
      <el-table-column type="index" label="序号" width="65" align="center" />
      <el-table-column label="月份" align="center" prop="month" />
      <el-table-column label="日期" align="center" prop="guardDate" />
      <el-table-column label="收费站" align="center" prop="deptName" v-if="deptId==101" />
      <el-table-column label="值班站长" align="center" prop="leaderName" />
      <el-table-column label="收费" align="center" prop="">
        <el-table-column label="白班" align="center" prop="chargeWhiteList">
        </el-table-column>
        <el-table-column label="夜班" align="center" prop="chargeBlackList">
        </el-table-column>
      </el-table-column>
      <el-table-column label="治超" align="center">
        <el-table-column label="白班" align="center" prop="excessWhiteList">
        </el-table-column>
        <el-table-column label="夜班" align="center" prop="excessBlackList">
        </el-table-column>
      </el-table-column>
      <el-table-column label="票证稽核" align="center">
        <el-table-column label="主办" align="center" prop="auditHostList">
        </el-table-column>
        <el-table-column label="协办" align="center" prop="auditJoinList">
        </el-table-column>
      </el-table-column>

      <el-table-column label="ETC发行" align="center" prop="etcPublicList" width="180">
        
      </el-table-column>
      <el-table-column label="办公" align="center" prop="officeList">
       
      </el-table-column>
      <el-table-column label="维修" align="center" prop="repairList">
       
      </el-table-column>
      <el-table-column label="后勤" align="center" prop="logisticsList">
        
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" v-if="deptId!=101">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['coordination:guard:edit']">修改</el-button>
          <el-button link type="primary" icon="Edit" @click="handleDelete(scope.row)" v-hasPermi="['coordination:guard:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" /> -->

    <!-- 添加或修改值班对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body class="duty">
      <el-form ref="guardRef" :model="form" :rules="rules" label-width="80px" >
        <el-row :gutter="10" class="mb8">
          <el-col :span="8">
            <el-form-item label="值班日期" prop="guardDate">
              <el-date-picker clearable v-model="form.guardDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择值班日期">
              </el-date-picker>
            </el-form-item>
          </el-col> <el-col :span="8">
            <el-form-item label="值班站长" prop="leaderName">
              <el-input  v-model="form.leaderName" placeholder="请输入"></el-input>
              <!-- <el-select v-model="form.leaderId" placeholder="请选择">
                <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId" />
              </el-select> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="center">值班和人员关联信息</el-divider>
        <!-- <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddTbCooGuardUser">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteTbCooGuardUser">删除</el-button>
          </el-col>
        </el-row> -->
        <el-table  style="width:100%" :data="tbCooGuardUserList" :row-class-name="rowTbCooGuardUserIndex" @selection-change="handleTbCooGuardUserSelectionChange"
          ref="tbCooGuardUser">
          <el-table-column label="序号" align="center" prop="index" width="65" />
          <el-table-column label="值班岗位" align="center" prop="poleType" width="400">
            <template #default="scope">
              <dict-tag :options="coo_guard_pole_type" :value="scope.row.poleType" />
            </template>
          </el-table-column>
          <el-table-column label="人员" align="center" prop="userId">
            <template #default="scope">
              <!-- <el-select class="inputDeep" v-model="scope.row.userId" placeholder="请选择" multiple>
                <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId" />
              </el-select> -->
              <el-input  v-model="scope.row.value" placeholder="请输入"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="人员调整" v-model="dutyDialog" width="1000px" append-to-body>
      <el-form ref="guardRef" :model="form" :rules="rules" label-width="120px" class="duty">
        <el-row :gutter="10" class="mb8">
          <el-col :span="12">
            <el-form-item label="调整人员" prop="userId">
              <el-select style="width: 100%;" v-model="form.userId" placeholder="请选择">
                <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="岗位" prop="poleType">
              <el-select style="width: 100%;" v-model="form.poleType" placeholder="请选择" >
                <el-option v-for="item in coo_guard_pole_type" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="调整后人员" prop="changeUserId">
              <el-select style="width: 100%;" v-model="form.changeUserId" placeholder="请选择" >
                <el-option v-for="item in userList" :key="item.userId" :label="item.userName" :value="item.userId" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="岗位" prop="poleType">
              <el-select style="width: 100%;" v-model="form.poleType" placeholder="请选择" :disabled="true">
                <el-option v-for="item in coo_guard_pole_type" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="调整开始日期" prop="beginDate">
              <el-date-picker style="width: 100%;" clearable v-model="form.beginDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择值班日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调整结束日期" prop="expireDate">
              <el-date-picker style="width: 100%;" clearable v-model="form.expireDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择值班日期">
              </el-date-picker>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

        <!-- 用户导入对话框 -->
        <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Guard">
import moment from 'moment'
import { getToken } from "@/utils/auth";
import { listGuard, getGuard, delGuard, addGuard, updateGuard ,editUser} from "@/api/coordination/guard";
import { getCAuditorUser } from "@/api/charge/cAuditor";
import { getCKInfo } from '@/utils/auth'
import { deptTreeSelect } from "@/api/system/user";
import { watch } from "vue";
const { proxy } = getCurrentInstance();

const { coo_guard_pole_type } = proxy.useDict('coo_guard_pole_type');

const guardList = ref([]);
const tbCooGuardUserList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedTbCooGuardUser = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const deptId = ref(Number(getCKInfo('deptId')))
const deptOptions = ref([])
const userList = ref([])
const dutyDialog=ref(false)
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/coordination/guard/importData"
});
const data = reactive({
  form:{deptId:deptId.value},
  queryParams: {
    // pageNum: 1,
    // pageSize: 10,
    deptId: deptId.value,
    leaderId: null,
    guardDate:deptId.value==101?moment().format("YYYY-MM-DD"):'',
    month:moment().format("YYYY-MM")
  },
  rules: {
    guardDate: [
      { required: true, message: "值班日期不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);



watch(() => coo_guard_pole_type.value, (val) => {
  val.forEach(element => {
    tbCooGuardUserList.value.push({ poleType: element.value, value: "" })
    // tbCooGuardUserList.value.push({ [element.value]:''})
  });
}, { immediate: true, deep: true })


/** 查询值班列表 */
function getList() {
  loading.value = true;
  listGuard(queryParams.value).then(response => {
    guardList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
}

function getUserList() {
  // ,postId:
  getCAuditorUser({ deptId: deptId.value }).then(response => {
    userList.value = response.rows;
  });
}
/** 导入按钮操作 */
function handleImport() {
  upload.title = "值班导入";
  upload.open = true;
};
/** 下载模板操作 */
function importTemplate() {
  proxy.download("/coordination/guard/importTemplate", {
  }, `值班管理_${new Date().getTime()}.xlsx`);
};
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};
// 取消按钮
function cancel() {
  dutyDialog.value=false;
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    // id: null,
  };

  proxy.resetForm("guardRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  // queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value={deptId:deptId.value}
  open.value = true;
  title.value = "添加值班";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  // dutyDialog.value = true;
  // open.value=true;
  const _id = row.id || ids.value;
  form.value.id=_id;
  getGuard(_id).then(response => {
    form.value = response.data;
    tbCooGuardUserList.value.forEach(item=>{
        item.value=form.value[item.poleType]
        })
    // tbCooGuardUserList.value = response.data.tbCooGuardUserList;
    open.value=true;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["guardRef"].validate(valid => {
    if (valid) {
      tbCooGuardUserList.value.forEach(item=>{
          form.value[item.poleType]=item.value
        })
      if (form.value.id != null) {
        // editUser(form.value).then(response => {
        //   proxy.$modal.msgSuccess("调用成功");
        //   dutyDialog.value = false;
        //   getList();
        // });
        updateGuard(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });

      } else {
        
        addGuard(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}



/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除值班编号为"' + _ids + '"的数据项？').then(function () {
    return delGuard(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 值班和人员关联序号 */
function rowTbCooGuardUserIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 值班和人员关联添加按钮操作 */
function handleAddTbCooGuardUser() {
  let obj = {};
  obj.userId = "";
  obj.poleType = "";
  tbCooGuardUserList.value.push(obj);
}

/** 值班和人员关联删除按钮操作 */
function handleDeleteTbCooGuardUser() {
  if (checkedTbCooGuardUser.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的值班和人员关联数据");
  } else {
    const tbCooGuardUsers = tbCooGuardUserList.value;
    const checkedTbCooGuardUsers = checkedTbCooGuardUser.value;
    tbCooGuardUserList.value = tbCooGuardUsers.filter(function (item) {
      return checkedTbCooGuardUsers.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleTbCooGuardUserSelectionChange(selection) {
  checkedTbCooGuardUser.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('coordination/guard/export', {
    ...queryParams.value
  }, `值班_${new Date().getTime()}.xlsx`)
}
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};
getList();
getDeptTree()
getUserList();
</script>


<style>
.inputDeep  .el-input__inner {
  min-height: 38px!important;
  height: 40px;
}
:deep(.el-input__inner) {
  min-height: 38px!important;
  height: 40px;
}
</style>